from flask import request, jsonify
from fullstack import app, api, db
from flask_restful import Resource
from fullstack.Models.food.FoodCategory import FoodCategory
from fullstack.utils import getCurrentTime, to_json, paginate

SECTION_URL = '/vue/api/category'


class AddCategory(Resource):
    def post(self):
        rest = request.json
        Category = FoodCategory()
        Category.name = rest['data']['name']
        Category.updated_time = Category.created_time = getCurrentTime()
        db.session.add(Category)
        db.session.commit()

        return jsonify(status=200)

    def get(self):
        sql = '''
        SELECT*
        FROM food_category
        '''
        result = db.engine.execute(sql)
        jsonData = list()
        for row in result:
            jsonData.append(to_json(FoodCategory, row))

        return jsonData


api.add_resource(AddCategory, SECTION_URL+'/add')


class CategoryList(Resource):
    def get(self):
        # 查询参数
        res = request.values
        query = res['query']
        pagenum = int(res['pagenum'])
        pagesize = int(res['pagesize'])
        ret = paginate(pagenum, pagesize)
        flag = True
        print('++++++++++++++++++++++++++++++++++++++++++++++++++')
        # query字符串为空
        if res['query']:
            sql = '''
            SELECT* 
            FROM food_category
            LIMIT {0},{1}
            '''.format(ret['limit'], ret['offset'])
            counts = FoodCategory.query.count()
        else:
            sql = '''
            SELECT* 
            FROM food_category
            WHERE name LIKE '%%{0}%%'
            '''.format(query)
            flag = False

        result = db.engine.execute(sql)
        responseData = dict()
        jsonData = list()

        for row in result:
            jsonData.append(to_json(FoodCategory, row))

        if not flag:
            counts = len(jsonData)

        responseData['total'] = counts
        # 当前页
        responseData['pagenum'] = 1
        responseData['categories'] = jsonData

        return responseData

    def delete(self):
        res = request.values
        id = int(res['id'])
        sql = '''
        DELETE FROM food_category
        WHERE id={0}
        '''.format(id)
        result = db.engine.execute(sql)
        return jsonify(status=200)

    def patch(self):
        rest = request.json.get('data')
        id = int(rest['id'])
        FoodCategory = FoodCategory.query.get(id)
        FoodCategory.name = rest['name']
        FoodCategory.updated_time = getCurrentTime()
        db.session.commit()
        return jsonify(status=200)


api.add_resource(CategoryList, SECTION_URL+'/list')
